package com.site.web.sys.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import com.site.domain.UserInfo;
import com.site.service.UserService;
import com.site.util.common.MD5Util;
import com.site.util.model.AjaxModel;

@Controller
@RequestMapping("/sys/")
public class UserController{
	
	private static Logger logger = LoggerFactory.getLogger(UserController.class);
	private static String SYS_FORWARD_LOGIN = "forward:/sys/login";
	private static String SYS_LOGIN = "redirect:/sys/login";
	private static String SYS_MAIN= "redirect:/sys/main";
	
	@Autowired
	private UserService userService;
	
	/**
	 * Purpose: 登录页面
	 * @author: liangjun
	 * @param request
	 * @param response
	 * @return: ModelAndView
	 */
	@RequestMapping("login")
	public ModelAndView login(HttpServletRequest request,HttpServletResponse response) {
		return new ModelAndView();
	}
	
	/**
	 * Purpose: 登录验证
	 * @author: liangjun
	 * @param request
	 * @param response
	 * @return: ModelAndView
	 */
	@RequestMapping(value="loginCheck",method=RequestMethod.POST)
	public ModelAndView loginCheck(HttpServletRequest request,HttpServletResponse response) {
		ModelAndView mav = new ModelAndView(SYS_FORWARD_LOGIN);
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String ip = getIP(request);
		logger.debug("登录用户："+username+" 登录IP:"+ip+"");
		if (null == password || password.equals("")) {
			mav.addObject("login_error", "\u8bf7\u8f93\u5165\u6b63\u786e\u7684\u767b\u5f55\u5bc6\u7801");//请输入正确的登录密码
		}
		try {
			UserInfo userInfo = userService.getUserInfoByName(username);
			if(null == userInfo){
				mav.addObject("login_error", "\u7528\u6237\u540d\u8f93\u5165\u4e0d\u6b63\u786e");//用户名输入不正确
			}else if(!userInfo.getUserPassword().equals(MD5Util.MD5(password))){
				mav.addObject("login_error", "\u7528\u6237\u5bc6\u7801\u8f93\u5165\u4e0d\u6b63\u786e");//用户密码输入不正确
			}else if(userInfo.getUserPassword().equals(MD5Util.MD5(password))){
				WebUtils.setSessionAttribute(request, "userInfo", userInfo);
				mav.setViewName(SYS_MAIN);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.debug("用户登录异常："+e.getMessage()+"");
			mav.addObject("login_error", "\u7528\u6237\u767b\u5f55\u5f02\u5e38");//用户登录异常
		}
		return mav;
	}
	
	/**
	 * Purpose: 退出登录
	 * @author: liangjun
	 * @param request
	 * @return: ModelAndView
	 */
	@RequestMapping("loginout")
	public ModelAndView logout(HttpServletRequest request) {
		WebUtils.setSessionAttribute(request, "userInfo", null);
		return new ModelAndView(SYS_LOGIN);
	}
	
	/**
	 * Purpose: 修改密码
	 * @author: liangjun
	 * @param request
	 * @param response
	 * @param password
	 * @return: AjaxModel
	 */
	@ResponseBody
	@RequestMapping("updPassword")
	public AjaxModel updPassword(HttpServletRequest request, HttpServletResponse response, String password) {
		AjaxModel aml = new AjaxModel();
		int retCode = 0;
		String retMsg = "";
		UserInfo userInfo = null;
		try {
			userInfo = (UserInfo) WebUtils.getSessionAttribute(request, "userInfo");
			if(null == userInfo){
				retCode = 0;
				retMsg = "请重新登录！";
				return aml;
			}
			if(null == password || "".equals(password)){
				retMsg = "请输入新密码";
			}else if(null != password && !"".equals(password)){
				userService.updateUserInfoByUserId(userInfo.getUserId(),MD5Util.MD5(password));//加密
				retCode = 1;
				retMsg = "修改成功";
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("修改异常:"+e.getMessage()+"");
			retMsg = "修改失败！";
		}
		aml.setRetCode(retCode);
		aml.setRetMsg(retMsg);
		return aml;
	}
	
	/**
	 * Purpose: 获取IP
	 * @author: liangjun
	 * @param request
	 * @return: String
	 */
	private static String getIP(HttpServletRequest request){
		String ip = request.getHeader("x-forwarded-for"); 
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	        ip = request.getHeader("Proxy-Client-IP"); 
	    } 
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	        ip = request.getHeader("WL-Proxy-Client-IP"); 
	    } 
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	        ip = request.getRemoteAddr(); 
	    } 
		return ip;
	}
	
}
